var socket;
var username = '';

function connectWebSocket() {
    username = document.getElementById("usernameInput").value;
    if (username) {
        //1、创建 WebSocket 实例对象
        socket = new WebSocket("ws://localhost:8080/ws?username=" + username);
        //2、建立连接并发送报文
        socket.onopen = function (event) {
            document.getElementById("messageInput").disabled = false;
            document.querySelector('button[onclick="sendMessage()"]').disabled = false;
        };
        //3、监听服务端返回数据
        socket.onmessage = function (event) {
            var data = JSON.parse(event.data);
            var chat = document.getElementById("chatMessages");
            var onlineUsersList = document.getElementById("onlineUsers");

            if (data.type === "userlist") {
                onlineUsersList.innerHTML = '';
                data.users.forEach(function (user) {
                    var userNode = document.createElement("li");
                    userNode.classList.add("onlineUser");
                    userNode.appendChild(document.createTextNode(user));
                    userNode.onclick = function () {
                        document.getElementById("messageInput").value = `@${user} `;
                    };
                    onlineUsersList.appendChild(userNode);
                });
            } else if (data.type === "message") {
                var messageNode = document.createElement("div");
                messageNode.classList.add("messageContainer");

                var usernameNode = document.createElement("span");
                usernameNode.classList.add("username");
                usernameNode.appendChild(document.createTextNode(data.username + ": "));
                messageNode.appendChild(usernameNode);

                var messageTextNode = document.createElement("span");
                messageTextNode.classList.add("messageText");
                messageTextNode.appendChild(document.createTextNode(data.message));
                messageNode.appendChild(messageTextNode);

                chat.appendChild(messageNode);
            }
        };
    } else {
        // alert('Please enter a username to connect.');
        $('#alertModal').modal('show');
    }
}

function sendMessage() {
    var message = $('#messageInput').val()
    if (message) {
        var toUser = extractToUser(message);
        var data = {
            type: "message",
            username: username,
            message: message,
            toUser: toUser
        };
        socket.send(JSON.stringify(data));
        $('#messageInput').val('');
    } else {
        alert('Please type a message to send.');
    }
}

function extractToUser(message) {
    var atIndex = message.indexOf('@');
    if (atIndex !== -1) {
        var spaceIndex = message.indexOf(' ', atIndex);
        if (spaceIndex !== -1) {
            return message.substring(atIndex + 1, spaceIndex);
        } else {
            return message.substring(atIndex + 1);
        }
    }
    return "";
}

